#include "TcpServer.hpp"
#include "Util/Protocol.hpp"
#include <memory>
using namespace ns_protocol;
Response Calculate(const Request &req) // 给一个请求，返回一个响应
{
    Response resp(req._x, req._y, req._op);
    switch (req._op)
    {
    case '+':
        resp._result = req._x + req._y;
        break;

    case '-':
        resp._result = req._x - req._y;
        break;

    case '*':
        resp._result = req._x * req._y;
        break;

    case '/':
        if (req._y == 0)
            resp._code = 1;
        else
            resp._result = req._x / req._y;
        break;

    case '%':
        if (req._y == 0)
            resp._code = 2;
        else
            resp._result = req._x % req._y;
        break;

    default:
        resp._code = 3;
        break;
    }
    return resp;
}

void NetCal(connection *conn, const string &Request)
{
    // 此时的Requset是一个完整的请求报文
    // 1.反序列化
    ns_protocol::Request req;
    req.DeSerialized(Request);

    // 2.业务处理，构建应答
    Response resp = Calculate(req);

    // 3.序列化 + 添加报头
    string respString = resp.Serialize();
    respString = Encode(respString);
    // cout << "respString:" << respString << endl;

    // 4.发送数据放到发送缓冲区，由服务器发送
    // send(conn->_sock, respString.c_str(), respString.size(), 0); // 不能直接发送
    conn->_outBuffer += respString;

    // 5.打开写事件关心，下次wait自动触发sender回调
    conn->_tsvr->EnableReanWrite(conn, true, true);
}

int main()
{
    unique_ptr<TcpServer> server(new TcpServer(8080));
    server->Start(NetCal);
    return 0;
}